import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../atoms/getuser';
import { tbfdsys } from '../../../atoms/db';

const logger = anylogger('pages/api/logo.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	src: string;
}

export default function base(key: string, default_src: string) {
	const handler = an48<Result>();

	handler.get(async (_req, res) => {
		try {
			const logo = await tbfdsys().first('value').where({
				key
			});
			if (logo && logo.value) {
				res.redirect(logo.value);
			} else {
				res.redirect(default_src);
			}
		} catch (error) {
			logger.trace(error);
			res.redirect(default_src);
		}
	})
		.put(async (req, res) => {
			logger.debug('body', req.body);
			const body = req.body as Message;
			try {
				const user = await getuser(req);
				if (!user || user.role !== 'admin') {
					res.json({
						ok: false,
						message: '当前用户无权限进行该操作'
					});
					return;
				}
				if (!body.src) {
					res.json({
						ok: false,
						message: '参数缺失'
					});
					return;
				}
				const logo = await tbfdsys().first('value').where({
					key
				});
				// update
				if (logo) {
					await tbfdsys().update({
						value: body.src
					})
						.where({ key });
				} else {
					// insert
					await tbfdsys().insert({
						key,
						value: body.src
					});
				}
				res.json({ ok: true });
			} catch (error) {
				logger.trace(error);
				res.json({
					ok: false,
					message: error.toString()
				});
			}
		});
	return handler;
}
